package QueueTest;

import java.util.LinkedList;
import java.util.Queue;

//利用 队列 实现 栈
public class MyStack1 {

    //创建两个栈
    private Queue<Integer> qu1;
    private Queue<Integer> qu2;

    public MyStack1() {
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();
    }

    public void push(int x) {
       if(!qu1.isEmpty()){
           qu1.offer(x);
       }else if(!qu2.isEmpty()){
           qu2.offer(x);
       }else{
           qu1.offer(x);
       }
    }

    //出
    public int pop() {
        if(empty()){
            return -1;//两个队列都为空，意味着当前的栈 为空
        }
        if(!qu1.isEmpty()){
           int len1 = qu1.size();
            for (int i = 0; i < len1-1; i++) {
                int value = qu1.poll();
                qu2.offer(value);
            }
            return qu1.poll();
        }else{
            int len2 = qu2.size();
            for (int i = 0; i < len2-1; i++) {
                int value = qu2.poll();
                qu1.offer(value);
            }
            return qu2.poll();
        }
    }

    public int top() {
        if(empty()){
            return -1;//两个队列都为空，意味着当前的栈 为空
        }
        if(!qu1.isEmpty()){
            int len1 = qu1.size();
            int value = -1;
            for (int i = 0; i < len1; i++) {
                value = qu1.poll();
                qu2.offer(value);
            }
            return value;
        }else{
            int len2 = qu2.size();
            int value = -1;
            for (int i = 0; i < len2; i++) {
                value = qu2.poll();
                qu1.offer(value);
            }
            return value;
        }

    }

    public boolean empty() {
        return qu1.isEmpty() && qu2.isEmpty();
    }
}
